<template>
    <div>
        <div><h1>商品类型</h1></div>
        <div>
            <el-button type="primary" @click="onAddRootType"
                >新增类型</el-button
            >
        </div>
        <div>
            <el-table
                :data="tableData"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
            >
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="name" label="类型名称" />
                <el-table-column prop="typeStatus" label="状态" />
                <el-table-column prop="typeTop" label="排序" />
                <el-table-column prop="typeImage" label="图片">
                    <template #default="scope">
                        <img v-if="scope.row.typeImage!=null" :src="scope.row.typeImage" style="width: 100px; height: 100px;" />
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            size="small"
                            @click="onAddType(scope.row)"
                            >新增</el-button
                        >
                        <el-button
                            type="success"
                            size="small"
                            @click="onEditType(scope.row)"
                            >编辑</el-button
                        >
                        <el-button
                            type="danger"
                            size="small"
                            @click="onDeleteType(scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <el-dialog
                v-model="dialogFormVisible"
                title="新增商品类型"
                width="500"
            >
                <el-form :model="form" ref="ruleFormRef" :rules="rules">
                    <el-form-item
                        label="分类名称"
                        :label-width="formLabelWidth"
                        prop="typeName"
                    >
                        <el-input v-model="form.typeName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="分类图片"
                        :label-width="formLabelWidth"
                        prop="typeImage"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            :show-file-list="false"
                            :headers="headers"
                            :on-success="handleAvatarSuccess"
                        >
                            <img
                                v-if="imageUrl"
                                :src="imageUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="排序" :label-width="formLabelWidth" prop="typeTop">
                        <el-input v-model="form.typeTop" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth" prop="typeStatus">
                        <el-radio-group v-model="form.typeStatus">
                            <el-radio :value="0">显示</el-radio>
                            <el-radio :value="1">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getTypeTree, addType } from "@/api/api";
import { ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'


const tableData = ref([]);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    typeId: null,
    typeImage: null,
    typeName: null,
    typePid: null,
    typeStatus: null,
    typeTop: null,
});

const imageUrl = ref('')
const headers = ref({
    token: sessionStorage.getItem('token')
})

const ruleFormRef = ref<FormInstance>()

const checkImage = (rule: any, value: any, callback: any) => {
    if(imageUrl.value == null || imageUrl.value == '') {
        return callback(new Error('请上传图片'));
    }
    else {
        return callback();
    }
    
}


const rules = ref({
    typeName: [
        { required: true, message: '请输入商品分类的名称', trigger: 'blur' },
    ],
    typeTop: [
        { required: true, message: '请输入商品分类的排序', trigger: 'blur' },
    ],
    typeStatus: [
        {
        required: true,
        message: '请选择商品分类的状态',
        trigger: 'change',
        },
    ],
    typeImage: [{ required: true, validator: checkImage, trigger: 'blur' }],
})

// 带表单校验的提交函数
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        // 表单校验通过了
        onSubmitAddType();
    } else {
        // 表单校验没通过
      console.log('error submit!', fields)
    }
  })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // 这是图片回显地址,response相当于res,使用的是全路径,所以少了一个data
  imageUrl.value = response.data;
}

//
const onSubmitAddType = () => {
    form.value.typeImage = imageUrl.value;
    addType(form.value).then((res) => {
        if (res.data.code == 200) {
            dialogFormVisible.value = false;
            ElMessage.success("添加成功");
            loadTypeTree();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 新增顶级类型
const onAddRootType = () => {
    console.log("新增类型");
    imageUrl.value = '';

    form.value = {
        typeId: null,
        typeImage: null,
        typeName: null,
        typePid: 0,
        typeStatus: null,
        typeTop: null,
    };
    dialogFormVisible.value = true;
};

// 新增子类型
const onAddType = (row: any) => {
    console.log("新增类型", row);
    form.value = {
        typeId: null,
        typeImage: null,
        typeName: null,
        typePid: row.id,
        typeStatus: null,
        typeTop: null,
    };
    imageUrl.value = '';
    dialogFormVisible.value = true;
};

const onEditType = (row: any) => {
    console.log("编辑类型", row);
};

const onDeleteType = (row: any) => {
    console.log("删除类型", row);
};

// 加载商品类型树
const loadTypeTree = () => {
    getTypeTree().then((res) => {
        console.log(res);
        if (res.data.code == 200) {
            tableData.value = res.data.data;
        }
    });
};

// 页面加载钩子函数
onMounted(() => {
    loadTypeTree();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
